<template>
  <!--配置节点-->
    <div>
        <common-title title-name="任务信息"/>
        <el-card class="m-b20" shadow="never">
            <el-form label-width="150px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="所属任务名称">
                            <el-input disabled :placeholder="taskNode.taskName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="任务计划时间范围">
                            <el-input disabled :placeholder="taskNode.taskStartTime + '-' + taskNode.taskEndTime"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="任务主要责任部门">
                            <el-input disabled :placeholder="taskNode.responsibleDepartmentName || '暂无'"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="任务责任人">
                            <el-input disabled :placeholder="taskNode.responsibleUserName || '暂无'"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <common-title title-name="节点信息"/>
        <div class="search-wrap m-b20" v-if="false">
            <el-button
                    size="large" color="#ff7b56"
                    style="color: #FFFFFF;"
                    @click="addHandle"
            >新增</el-button>
            <el-button
                    size="large"
                    color="#ff7b56"
                    style="color: #FFFFFF;"
                    @click="deleteHandle"
            >删除</el-button>
            <el-button
                    size="large"
                    color="#ff7b56"
                    style="color: #FFFFFF;"
                    @click="moveUpHandle"
            >上移</el-button>
            <el-button
                    size="large"
                    color="#ff7b56"
                    style="color: #FFFFFF;"
                    @click="moveDownHandle"
            >下移</el-button>
            <el-button
                    size="large"
                    color="#ff7b56"
                    style="color: #FFFFFF;"
                    @click="saveSetting"
            >保存设置</el-button>
        </div>
        <public-table
                border
                :is-paging="false"
                :page="page"
                :table-data="tableData"
                :table-option="tableOption"
                :header-cell-style="{'background':'#f7f7fa'}"
                @handle-selection-change="handleSelectionChange"
        >
            <template #actionName="scope">
                <span>{{filterAction(scope.row)}}</span>
            </template>
            <template #buttons="scope">
                <el-button
                    v-if="
                  (scope.row.status == -1 &&
                    scope.row.auditStatus == 2 &&
                    scope.row.isOverdue == 1) ||
                  (scope.row.status == -1 &&
                    scope.row.auditStatus == 0 &&
                    scope.row.isOverdue == 0) ||
                    (scope.row.status === 3)
                "
                        size="large"
                        class="button_view"
                        @click="operate(scope.row,scope.row.status===3?'operate2':'operate')"
                >{{filterAction(scope.row)}}</el-button>

                <el-button
                            v-if="
                          (scope.row.auditStatus == 3 && scope.row.status == -1) ||
                          scope.row.status ===1 || scope.row.status ===2 ||
                          (scope.row.businessAuditStatus == 3 && scope.row.status == -1)
                        "
                        size="large"
                        class="button_view"
                        @click="operate(scope.row,'view')"
                >查看</el-button>

                <el-button
                    v-if="
                  scope.row.isOverdue == 1 &&
                  scope.row.status == -1 &&
                  (scope.row.auditStatus == 0 || scope.row.auditStatus == 3)
                "
                @click="anticipateHandler(scope.row, '逾期上报')"
                size="large"
                class="button_view"
                >逾期上报</el-button>

                <el-button
                    v-if="scope.row.auditStatus == 1 && scope.row.status == -1"
                    size="large"
                    class="button_view"
                    @click="anticipateHandler(scope.row, '审核')"
                >审核</el-button>
            </template>
        </public-table>
    </div>

    <public-form-popup
            ref="publicFormPopupRef"
            :popup-params="{
          width:'40%',
          title:'新增实施任务节点',
          loadingText:'表单数据提交中...',
          confirmButtonTitle:'确认'
      }"
            :form="form"
            :fields="fields"
            popup-type="add"
            :confirm-params="{
           fun:(form,isLoading)=>{
              addNodes(form,isLoading);
           }
      }"
    />

    <!-- 上次实施成果   -->
    <over-dialog
        ref="overDialogRef"
        @refreshList="projectTaskList"
    />

    <!-- 上传合同原件   -->
    <contract-dialog
        ref="contractDialogRef"
        @refreshList="projectTaskList"
    />

    <!-- 逾期上报   -->
   <late-reporting
       ref="lateReportingRef"
       @refreshList="projectTaskList"
   />
</template>

<script setup>
import PublicTable from "@/components/PublicTable.vue";
import {onMounted, reactive, ref} from "vue";
import {investmentProjects, taskApi} from "@/api/investment";
import {useRouter} from "vue-router";
import {ElButton, ElMessage,ElCard,ElForm,ElFormItem,ElRow,ElCol} from "element-plus";
import PublicFormPopup from "@/components/publicFormPopup.vue";
import {useStore} from "vuex";
import CommonTitle from "@/components/CommonTitle.vue";
import OverDialog from "../components/overDialog.vue";
import ContractDialog from "../components/contractDialog.vue";
import LateReporting from "../components/anticipatLoading.vue";

const router = useRouter();
const getProjectTaskId = router.currentRoute.value.params.projectTaskId;
const getTaskName = router.currentRoute.value.params.taskName;
const store = useStore();

const currentIndex = ref(0);
const tableData = ref([]);
const tableOption = ref([
  { label: "任务节点", prop: "itemName", minWidth: 100 },
  { label: "节点开始时间", prop: "planStartTime", minWidth: 120 },
  { label: "节点完成时间", prop: "planEndTime", minWidth: 120 },
  { label: "实施行为类型", prop: "actionName", slot: true, minWidth: 120 },
  {
    label: "状态", prop: "status", formatter: (val) => {
      return { '-1': '未开始', '1': '进行中', '2': '已完成', '3': '已驳回' }[val] || '-';
    }, minWidth: 100
  },
  { label: "操作", prop: "buttons", slot: true, minWidth: 100 },
]);

const page = reactive({
    total: 0,
    current: 1,
    size: 9999
});

const form = reactive({
    taskName:getTaskName,
    itemName:'',
    responsibleDepartmentId:store.state.user.departmentId,
    departmentName:store.state.user.departmentName,
    responsibleUserId:store.state.user.userId,
    username:store.state.user.username,
    actionId:'',
    planStartTime:'',
    planEndTime:'',
});

const fields = ref([
    {
        label:'所属任务名称',
        type:'input',
        key:'taskName',
        required: false,
        width:300,
        disabled:true,
    },
    {
        label:'任务节点名称',
        type:'input',
        key:'itemName',
        width:300,
        message:'请输入任务节点名称',
        placeholder: '请输入任务节点名称',
        event:'blur'
    },
    {
        label:'责任部门',
        type:'input',
        key:'departmentName',
        required: false,
        width:300,
        disabled:true,
    },
    {
        label:'责任人',
        type:'input',
        key:'username',
        required: false,
        width:300,
        disabled:true,
    },
    {
        label: '实施行为',
        type:'select',
        key:'actionId',
        width:300,
        clearable:true,
        placeholder:'请选择实施行为',
        message:'请选择实施行为',
        event:'change',
        options:{
            labelKey:'actionName',
            valueKey:'actionId',
            list:[]
        },
        /* interfaceConfig:{
             fileName:'investment',
             apiPath:'investmentProjects.getActionList'
         }*/
    },
    {
        label:'节点计划实施期限',
        type:'datetimerange',
        key:'valueTime',
        width:300,
        message:'请选择节点计划实施期限',
        placeholder: '请选择节点计划实施期限',
        event:'change',
        fun:(e)=>{
            if(!e){
                form.planStartTime = '';
                form.planEndTime = '';
            }
            if(e){
                form.planStartTime = e[0];
                form.planEndTime = e[1];
            }
        }
    },
]);

/**
 * table被选中时
 * @param e
 */
const currentRow = ref([]);
const handleSelectionChange = (e) => {
    currentRow.value = e;
}

/**
 * 新增
 */
const publicFormPopupRef = ref(null);
const addHandle = () => {
    publicFormPopupRef.value.open();
}

/**
 * 删除
 */
const deleteHandle = () => {
    if(currentRow.value.length===0){
        return ElMessage.warning('请选择要操作的项!');
    }
    let i = '';
    currentRow.value.forEach((item)=>{
        tableData.value.forEach((val,index)=>{
            if(item.uuid === val.uuid){
                i = index;
                tableData.value.splice(index,1);
            }
        });
    });
    if(i!==''){
        sort(tableData.value);
    }
    currentIndex.value = tableData.value.length -1;
}

/**
 * 上移
 */
const moveUpHandle = () => {
    if(currentRow.value.length===0){
        return ElMessage.warning('请选择要操作的项!');
    }
    let uuid = currentRow.value[0].uuid;
    let index = tableData.value.findIndex(x=>x.uuid===uuid);
    if(index===-1)return;
    if(tableData.value[index-1]===undefined)return;
    tableData.value.splice(index-1,0, tableData.value[index]);
    tableData.value.splice(index+1,1);
}

/**
 * 下移
 */
const moveDownHandle = () => {
    if(currentRow.value.length===0){
        return ElMessage.warning('请选择要操作的项!');
    }
    let uuid = currentRow.value[0].uuid;
    let index = tableData.value.findIndex(x=>x.uuid===uuid);
    if(index===-1)return;
    if(tableData.value.length < (index+2)) return;
    tableData.value.splice(index+2,0, tableData.value[index]);
    tableData.value.splice(index,1);
}

/**
 * 排序
 * @param tableData
 */
const sort = (tableData) => {
    tableData.forEach((item,index)=>{
        item.sort = index + 1;
    });
    return tableData;
}

/**
 * 节点配置统一操作
 */
const operateTaskNode = (params,callback,err_callback) => {
    investmentProjects.operateTaskNode(params).then(res=>{
        if(res.code === '200'){
            ElMessage.success('操作成功!');
            if(callback)callback(res);
        }else{
            if(err_callback)err_callback();
        }
    });
}

/**
 * 保存设置
 */
const saveSetting = () => {
    if(tableData.value.length===0){
        return ElMessage.warning('节点不能为空,请添加节点!');
    }
    let params = {
        projectTaskId:getProjectTaskId,
        nodeDtoList:sort(tableData.value)
    }
    operateTaskNode(params,()=>{
        getTaskNodeList(getProjectTaskId);
    });
}

/**
 * 新增节点
 * @param data
 * @param isLoading
 */
const addNodes = (data,isLoading) => {
    isLoading.value = true;
    let params = {
        ...data,
        sort:currentIndex.value++,
        uuid:new Date().getTime().toString() + currentIndex.value,
    }
    tableData.value.push(JSON.parse(JSON.stringify(params)));
    setTimeout(()=>{
        isLoading.value = false;
        publicFormPopupRef.value.close();
        ElMessage.success('新增成功!');
    },1000);
}

/**
 * 查节点
 * @param taskId
 */
const taskNode = ref({});
const getTaskNodeList = (taskId) => {
    investmentProjects.getTaskNodeList(taskId).then(res=>{
        if(res.code === '200'){
            res.data.taskDetailItemVos.forEach((item,index)=>{
                item.uuid = new Date().getTime().toString()+index
            });
            taskNode.value = res.data;
            tableData.value = res.data.taskDetailItemVos;
            console.log('tableData.value',tableData.value)
        }
    });
}

/**
 * 实施行为
 */
const getActionList = () => {
    investmentProjects.getActionList().then(res=>{
        if(res.code === '200'){
            fields.value[4].options.list = res.data;
        }
    })
}

/**
 * 筛选actionName
 * @param row
 */
const filterAction = (row) => {
    if(row.actionName){
        return row.actionName;
    }
    if(!row.actionId){
        return '暂无';
    }
    return  fields.value[4].options.list.filter((item)=>{
        if(item.actionId === row.actionId){
            return item;
        }
    })[0].actionName;
}

/**
 * 操作
 */
const overDialogRef = ref(null);
const contractDialogRef = ref(null);
const operate = (row,type) => {
    let isLook = {'operate':0,'view':1,'operate2':2}[type];
    switch (row.actionId) {
        case '1': // 上传实核成果
            // publicFormPopupRef2.value.open();
            overDialogRef.value.state.centerDialogVisible = true
            overDialogRef.value.state.businessId = row.businessId
            overDialogRef.value.state.projectTaskId = row.projectTaskId
            overDialogRef.value.state.type = 0
            overDialogRef.value.state.isLook = isLook;
            overDialogRef.value.state.itemId = row.itemId
            break;
        case '2': //  组织会议 (产品说没有)

            break;
        case '3': // 发起招采需求议题请示
            router.push({path:`/investmentProjectManagement/investmentProjects/investmentProjectInformation/task/issueApprovalForm/${taskNode.value.projectId}/${getProjectTaskId}/${row.itemId}/${isLook}`});
            break;
        case '4': // 发起招采需求业务请示
            router.push({path:`/investmentProjectManagement/investmentProjects/investmentProjectInformation/task/businessApprovalForm/${taskNode.value.projectId}/${getProjectTaskId}/${row.itemId}/${isLook}`});
            break;
        case '5':// 上报决策会议名
            router.push({path:`/investmentProjectManagement/investmentProjects/investmentProjectInformation/task/decisionMakingMeetings/${taskNode.value.projectId}/${getProjectTaskId}/${row.itemId}/${isLook}`})
            break;
        case '6':// 推荐服务单位
            router.push({path:`/investmentProjectManagement/investmentProjects/investmentProjectInformation/task/serviceUnit/${taskNode.value.projectId}/${getProjectTaskId}/${row.itemId}/${isLook}`});
            break;
        case '7':// 提供合同初稿
            router.push({path:`/investmentProjectManagement/investmentProjects/investmentProjectInformation/task/contractDraft/${taskNode.value.projectId}/${getProjectTaskId}/${row.itemId}/0/${isLook}`});
            break;
        case '8'://  发起招标(选)合同会审
            router.push({path:`/investmentProjectManagement/investmentProjects/investmentProjectInformation/task/contractDraft/${taskNode.value.projectId}/${getProjectTaskId}/${row.itemId}/1/${isLook}`});
            break;
        case '9': // 上传已签章的合同原件
            contractDialogRef.value.state.dialogVisible = true
            contractDialogRef.value.state.businessId = row.businessId
            contractDialogRef.value.state.projectTaskId = row.projectTaskId
            contractDialogRef.value.state.type = 0
            contractDialogRef.value.state.itemId = row.itemId
            break;
    }
}

/**
 * 查询任务列表
 */
const projectTaskList = () => {
    getTaskNodeList(getProjectTaskId);
}

/**
 * 按钮
 */
const lateReportingRef = ref(null);
const anticipateHandler = (row, type) => {
    lateReportingRef.value.open(row, type);
}

onMounted(()=>{
    getActionList();
    getTaskNodeList(getProjectTaskId);
});
</script>

<style scoped>

</style>
